/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package banksystem;

import java.awt.Color;
import java.awt.event.ItemEvent;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

/**
 *
 * @author conra_000
 */
public class CreateCDFrame extends javax.swing.JFrame {
	Controller mController = null;
	HashMap<Long, CertificateOfDeposit> mCDs;
	/**
	 * Creates new form CreateCDFrame
	 */
	public CreateCDFrame(Controller controller,  HashMap<Long, CertificateOfDeposit> CDs) {
		initComponents();
		mController = controller;
		mCDs = CDs;
		
		CDPackage selectedCDPackage = this.packageComboBox.getItemAt(0);
		this.periodLabel.setText(Integer.toString(selectedCDPackage.getPeriod()));
		this.interestLabel.setText(Double.toString(selectedCDPackage.getInterestRate()));
		this.minLabel.setText(Double.toString(selectedCDPackage.getMinimumBalance()));
		this.penaltyLabel.setText(Double.toString(selectedCDPackage.getPenalty())+" + 3%");
		this.errorLabel.setVisible(false);

	}

	
	
	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        packageComboBox = new JComboBox<CDPackage>();
        jLabel3 = new javax.swing.JLabel();
        periodLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        interestLabel = new javax.swing.JLabel();
        buyButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        errorLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        minLabel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        penaltyLabel = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        amountTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Buy Certificate of Deposit");

        jLabel2.setText("Select Package:");

        packageComboBox.setModel(new DefaultComboBoxModel<>(CDPackage.values()));
        packageComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                packageComboBoxItemStateChanged(evt);
            }
        });

        jLabel3.setText("Period:");

        periodLabel.setText("Minutes");

        jLabel4.setText("Interest Rate:");

        interestLabel.setText("0.0%");

        buyButton.setText("Buy");
        buyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buyButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        errorLabel.setText("Error: ");

        jLabel5.setText("Min Deposit:");

        minLabel.setText("0");

        jLabel6.setText("Early Sell Penalty:");

        penaltyLabel.setText("1");

        jLabel7.setText("Deposit:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(121, 121, 121)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel7)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(penaltyLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(minLabel))
                    .addComponent(errorLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(periodLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(interestLabel))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(buyButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton))
                    .addComponent(jLabel2)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(packageComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(amountTextField))
                .addContainerGap(125, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(packageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(periodLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(interestLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(minLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(penaltyLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(amountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addComponent(errorLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buyButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void packageComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_packageComboBoxItemStateChanged
		JComboBox<AccountType> tempComboBox; 
		CDPackage selectedCDPackage;
		this.errorLabel.setVisible(false);
		
		try{
			tempComboBox = (JComboBox<AccountType>)evt.getSource();
			selectedCDPackage = (CDPackage) tempComboBox.getSelectedItem();
		}catch(ClassCastException e)
		{
			this.errorLabel.setText("Error: " + e.getLocalizedMessage());
			this.errorLabel.setVisible(true);
			return;
		}
		if(evt.getStateChange() == ItemEvent.SELECTED)
		{ 
			this.periodLabel.setText(Integer.toString(selectedCDPackage.getPeriod()));
			this.interestLabel.setText(Double.toString(selectedCDPackage.getInterestRate()));
			this.minLabel.setText(Double.toString(selectedCDPackage.getMinimumBalance()));
			this.penaltyLabel.setText(Double.toString(selectedCDPackage.getPenalty())+" + 3%");
		}
	}//GEN-LAST:event_packageComboBoxItemStateChanged

	private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
		mController.SaveAndRestart(this);
	}//GEN-LAST:event_cancelButtonActionPerformed

	private void buyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buyButtonActionPerformed
		CDPackage type; 
		double amount;
		
		try{
			type = (CDPackage) this.packageComboBox.getSelectedItem();
		}catch(ClassCastException e)
		{
			this.errorLabel.setText("Error: " + e.getLocalizedMessage());
			this.errorLabel.setVisible(true);
			return;
		}
		try{
			amount = this.currencyToDouble(this.amountTextField.getText());
		}catch(NumberFormatException e){
			this.errorLabel.setText("Error: Please Enter A Valid Amount");
			this.errorLabel.setVisible(true);
			return;
		}
		try{
			if(amount >= type.getMinimumBalance())
			{
				this.mController.CreateCD(createName(type), type, amount);
			}else{
				this.minLabel.setForeground(Color.red);
			}
		}catch(NullPointerException e){
			this.errorLabel.setText("Error: " + e.getLocalizedMessage());
			this.errorLabel.setVisible(true);
			throw(e);
		}
	}//GEN-LAST:event_buyButtonActionPerformed

	protected double currencyToDouble(String str) 
			throws NumberFormatException, NullPointerException
	{
		double num;
		
		if(str.matches("\\$?[0-9]*\\.?[0-9]{0,2}"))
		{
			str = str.replaceFirst("[$]", "");
			num = Double.valueOf(str);
		}else{
			throw new NumberFormatException("Invalid Currency");
		}
		
		return num;
	}
	
	protected String createName(CDPackage type)
	{
		int j = 1;
		String tmp = null;
		CertificateOfDeposit account;
		
		for(Iterator<CertificateOfDeposit> i = this.mCDs.values().iterator(); i.hasNext(); )
		{
			
			account = i.next();
			if(account.getType() != null)
			{	
				if(account.getPackage() == type)
				{
					tmp = account.getName();
				}
			}
		}
		
		if(tmp != null)
		{
			j = Integer.valueOf(tmp.substring(tmp.lastIndexOf(' ') + 1));
			j++;
		}
		
		return type.toString() + " " + j;
	}
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField amountTextField;
    private javax.swing.JButton buyButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JLabel interestLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel minLabel;
    private javax.swing.JComboBox<CDPackage> packageComboBox;
    private javax.swing.JLabel penaltyLabel;
    private javax.swing.JLabel periodLabel;
    // End of variables declaration//GEN-END:variables
}
